# -*- coding: utf-8 -*-

import urllib
import logging
import sys
import random
import time
from optparse import OptionParser

from django.db import connection, DatabaseError 

from web.service.HttpReader import HttpReader
from companyregister_parser import *
from companyregister_exception import ObchodnyRegisterDetailException

reload(sys)
sys.setdefaultencoding('Cp1252') #@UndefinedVariable

logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)

MAX_BREAK_SEC = 300

def takeABreak():
	return	
	logging.info('Taking a break...')
	time.sleep(int(MAX_BREAK_SEC * random.random()))

def main():
	parser = OptionParser()
	parser.add_option("--obchodny_vestnik_id", dest="ov_id", help="parse this <ov_id> issue of obchodny vestnik")	
	(options, args) = parser.parse_args()
				
	httpReader = HttpReader()
	random.seed()		
	try:
		ov_last_issue_id = None
		if not options.ov_id:
			logging.info('Fetching latest issue of Obchodny vestnik...')	
			content = httpReader.read("https://portal.justice.sk/PortalApp/ObchodnyVestnik/Web/Zoznam.aspx", encode = True)
			obchodnyVestnikZoznamParser = ObchodnyVestnikZoznamParser()
			obchodnyVestnikZoznamParser.parse(content)
			ov_last_issue_id = obchodnyVestnikZoznamParser.get_last_issue_id();			
			logging.info('Got last issue: %s' % (ov_last_issue_id))
			ov_last_issue_id = int(ov_last_issue_id) - 1
			logging.info('Will parse issue: %s' % (ov_last_issue_id))
		else:
			ov_last_issue_id = options.ov_id
		if ov_last_issue_id:
			try:
				logging.info('Fetching details of Obchodny vestnik issue %s...' % ov_last_issue_id)
				content = httpReader.read("https://portal.justice.sk/PortalApp/ObchodnyVestnik/Web/Detail.aspx?IdOVod=%s" % ov_last_issue_id, encode = True)			
				obchodnyVestnikDetailParser = ObchodnyVestnikDetailParser()
				obchodnyVestnikDetailParser.parse(content)			
				new_companies = obchodnyVestnikDetailParser.get_new_company_list()
				logging.info('Number of new companies: %d' % len(new_companies))	 			
				for new_company in new_companies:
					new_company_win1250_encoded = new_company.encode('windows-1250', 'ignore')																						
					new_company_cp1252_encoded = new_company.encode('Cp1252', 'ignore')										
					try:						
						logging.info('Fetching OR link of company "%s"...' % new_company_cp1252_encoded)
						content = httpReader.read("http://www.orsr.sk/hladaj_subjekt.asp?OBMENO=%s&PF=0&SID=0&R=on" % urllib.quote_plus(new_company_win1250_encoded), encode = True)								
						obchodnyRegisterCompanyZoznamParser = ObchodnyRegisterCompanyZoznamParser(new_company)				
						obchodnyRegisterCompanyZoznamParser.parse(content)
						new_company_link = obchodnyRegisterCompanyZoznamParser.get_company_link()
						if new_company_link:											
							#new_company_link="http://www.orsr.sk/vypis.asp?ID=233482&SID=9&P=0"															
							try:																
								logging.info('Fetching OR details of company "%s" from link %s...' % (new_company_cp1252_encoded, new_company_link))														
								content = httpReader.read(new_company_link, encode = True)
								orDetailFactoryParser = ObchodnyRegisterDetailFactoryParser(new_company_link)
								orDetailFactoryParser.parse(content)
								company_detail_parser = orDetailFactoryParser.get_company_detail_parser()
								company_detail_parser.parse(content)
								company = company_detail_parser.get_company()															
								logging.info(company.dump().encode('Cp1252', 'ignore'))
#===============================================================================
#								for person in company.person_list.all():
#									try:
#										first_name_win1250_encoded = person.first_name.encode('windows-1250', 'ignore')
#										last_name_win1250_encoded = person.last_name.encode('windows-1250', 'ignore')
#										logging.info('Fetching companies "%s %s" has been associated with...' % (first_name_win1250_encoded, last_name_win1250_encoded))
#										content = httpReader.read("http://orsr.sk/hladaj_osoba.asp?PR=%s&MENO=%s&SID=0&T=f0" % (urllib.quote_plus(last_name_win1250_encoded), urllib.quote_plus(first_name_win1250_encoded)), encode = True)
#										obchodnyRegisterPersonZoznamParser = ObchodnyRegisterPersonZoznamParser()
#										obchodnyRegisterPersonZoznamParser.parse(content)
#										company_person_list = obchodnyRegisterPersonZoznamParser.get_company_person_list()
#										pass
#									except ObchodnyRegisterDetailException, e:
#										pass																																																																																				
#									except Exception, e:																												
#										pass																								
#===============================================================================
							except ObchodnyRegisterDetailException, e:
								logging.error('Failed to fetch OR details of company "%s", reason: %s' % (new_company_cp1252_encoded, e))
							except Exception, e:																
								logging.error('Failed to fetch OR details of company "%s", reason: %s' % (new_company_cp1252_encoded, e))
								if isinstance(e, DatabaseError):
									connection._rollback()								
						else:
							logging.error('Company link is empty!')
					except Exception, e:
						logging.error('Failed to fetch OR link of company "%s", reason: %s' % e)
					
					takeABreak()
				
			except Exception, e:
				logging.error('Failed to fetch details of Obchodny vestnik issue %s, reason: %s' % (ov_last_issue_id, e))														
		else:
			logging.error('Last issue is empty!')						
	except Exception, e:			
		logging.error('Failed to fetch latest issue of Obchodny vestnik, reason: %s' % e)

if __name__ == "__main__":
	main()